package com.cal.calonecal.advice;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    // 处理所有接口数据验证异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Map<String,Object> map = new HashMap<>();
        e.printStackTrace();
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        map.put("code",400);
        map.put("msg","参数异常");
        return map;
    }

    // 处理请求路径没映射上的异常
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Object httpMessageNotReadableException(HttpMessageNotReadableException e) {
        Map<String,Object>map = new HashMap<>();
        map.put("code",400);
        map.put("msg",e.getMessage());
        e.printStackTrace();
        return map;
    }

    // 处理主键冲突异常
    @ExceptionHandler(value = DuplicateKeyException.class)
    public Object handleDuplicateKeyException(DuplicateKeyException e) {
        Map<String,Object>map = new HashMap<>();
        map.put("code",400);
        map.put("msg",e.getMessage());
        return map;
    }

    // 处理所有检测异常
//    @ExceptionHandler(value = CheckException.class)
//    public Result handleCheckException(CheckException e) {
//        log.info("handleCheckException");
//        e.printStackTrace();
//        CodeMsg codeMsg = new CodeMsg(100, e.getMessage());
//        //清除语言
//        UserLocaleUtils.clear();
//        return Result.error(codeMsg);
//    }

    // 处理所有的运行时异常
    @ExceptionHandler(value = RuntimeException.class)
    public Object handlerRuntimeException(RuntimeException e) {
        Map<String,Object> map = new HashMap<>();
        e.printStackTrace();
        map.put("code",400);
        map.put("msg",e.getMessage());
        return map;
    }

    // 处理其他异常(比如系统异常 : 数据库连接不上, 数据库连接超时等)
    @ExceptionHandler(value = Exception.class)
    public Object handlerException(Exception e) {
        Map<String,Object>map = new HashMap<>();
        e.printStackTrace();
        map.put("code",400);
        map.put("msg",e.getMessage());
        return map;
    }

}